package com.doubao.notepad_blog_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.notepad_blog_backend.common.exception.ApiAsserts;
import com.doubao.notepad_blog_backend.domain.BmsFollow;
import com.doubao.notepad_blog_backend.domain.BmsPost;
import com.doubao.notepad_blog_backend.domain.UmsUser;
import com.doubao.notepad_blog_backend.dto.LoginDTO;
import com.doubao.notepad_blog_backend.dto.RegisterDTO;
import com.doubao.notepad_blog_backend.mapper.BmsFollowMapper;
import com.doubao.notepad_blog_backend.mapper.BmsPostMapper;
import com.doubao.notepad_blog_backend.mapper.UmsUserMapper;
import com.doubao.notepad_blog_backend.service.UmsUserService;
import com.doubao.notepad_blog_backend.jwt.JwtUtil;
import com.doubao.notepad_blog_backend.utils.MD5Utils;
import com.doubao.notepad_blog_backend.utils.RedisUtil;
import com.doubao.notepad_blog_backend.vo.ProfileVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class UmsUserServiceImpl extends ServiceImpl<UmsUserMapper, UmsUser> implements UmsUserService {

    @Resource
    private BmsPostMapper postMapper;
    @Resource
    private BmsFollowMapper followMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public UmsUser register(RegisterDTO registerDTO) {
        // 查询是否有相同的用户名
        String userName = registerDTO.getName();
        String email = registerDTO.getEmail();
        LambdaQueryWrapper<UmsUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsUser::getUsername, userName)
                .or()
                .eq(UmsUser::getEmail, email);
        UmsUser umuser = this.getOne(queryWrapper);
        if (!ObjectUtils.isEmpty(umuser)) {
            ApiAsserts.fail("账号或邮箱已存在");
        }

        // 否则注册
        UmsUser umsUser = UmsUser.builder()
                .username(userName)
                .alias(userName)
                .password( MD5Utils.getPwd( registerDTO.getPass() ) )
                .email(email)
                .createTime(new Date())
                .status(true)
                .build();
        this.save(umsUser);

        return umsUser;
    }

    @Override
    public UmsUser getUserByUsername(String username) {
        return baseMapper.selectOne( new LambdaQueryWrapper<UmsUser>( ).eq( UmsUser::getUsername,username ) );
    }

    @Override
    public String login(LoginDTO dto) {
        String token = null;
        try{
            UmsUser user = getUserByUsername( dto.getUsername() );
            if (ObjectUtils.isEmpty(user)) {
                ApiAsserts.fail("用户名或邮箱不存在");
            }
            String encodePwd = MD5Utils.getPwd( dto.getPassword() );
            if(!encodePwd.equals( user.getPassword() )){
                ApiAsserts.fail( "密码错误" );
            }
            token = JwtUtil.generateToken( String.valueOf( user.getUsername() ) );
            //token加入redis
            redisUtil.set("token",token,60*5);
        }catch (Exception e){
            log.warn( "用户不存在or密码验证失败="+ dto.getUsername() );
        }
        return token;
    }


    /**
     * 按userId获取文章数和粉丝数
     * @param userId
     * @return ProfileVO
     */
    @Override
    public ProfileVO getUserProfile(String userId) {
        ProfileVO profile = new ProfileVO();
        UmsUser user = baseMapper.selectById(userId);
        BeanUtils.copyProperties(user, profile);
        // 用户文章数
        int count = postMapper.selectCount(new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getUserId, userId));
        profile.setPostCount(count);
        // 粉丝数
        int followers = followMapper.selectCount((new LambdaQueryWrapper<BmsFollow>().eq(BmsFollow::getParentId, userId)));
        profile.setFollowerCount(followers);
        return profile;
    }



}
